<?php
class ObjectController extends Zend_Controller_Action
{

    public function init()
    {
        $this->table = new Default_Model_DbTable_Object();
        $info = $this->table->info();
        $this->primary = $info['primary'][1];
        $this->cols = $info['cols'];

        $this->form = new Default_Form_Object();

        $this->locale = Zend_Registry::get('Zend_Locale');

        $this->url = 'http://'.$_SERVER['SERVER_NAME'];//.$this->getFrontController()->getBaseUrl();

        $this->urlParams = null;
        if (strlen($this->_getParam('by'))) {
            $this->urlParams .= '/by/'.$this->_getParam('by');
        }
        if (strlen($this->_getParam('sort'))) {
            $this->urlParams .= '/sort/'.$this->_getParam('sort');
        }
        if (strlen($this->_getParam('page'))) {
            $this->urlParams .= '/page/'.$this->_getParam('page');
        }


        Zend_Loader::loadClass('My_Message');
        $this->message = new My_Message('link');

    }

    public function indexAction()
    {
        $result = $this->table->fetchAll(
            $this->table->select()
                ->order($this->_getParam('by', $this->primary).' '.$this->_getParam('sort', 'ASC'))
            );

        $paginator = Zend_Paginator::factory($result->toArray());
        $paginator->setItemCountPerPage(10);
        $paginator->setCurrentPageNumber($this->_getParam('page', 1));

        $this->view->fields = array(
                'id'     => 'ID',
                'name'  => 'Nosaukums',
            );

        $editUrl = $this->view->url(
            array(
                'controller' => 'object',
                'action' => 'edit',
                'id' => '{ID}'
            )
        );

        $deleteUrl = $this->view->url(
            array(
                'controller' => 'object',
                'action' => 'delete',
                'id' => '{ID}'
            )
        );

        $this->view->options = array(
            'label' => 'Opcijas',
            'primary' => $this->primary,
            'options' => array(
                'Labot' => $editUrl,
                'Dzēst' => $deleteUrl
            )
        );

        $this->view->paginator = $paginator;
    }

    public function addAction()
    {
        // validate form and save new data
        if ($this->_request->isPost()) {
            $values = $this->_request->getPost();

            // prepare values
            foreach ($this->cols AS $column) {
                if ($column == 'data') {
                    /* if plugin, then save in data columns serialized plugin
                     * Array(
                     *       [plugins] => Array(
                     *           [0] => Array(
                     *               [name] => plugin_content
                     *               [id] =>
                     *           )
                     *       )
                     *  )
                     */
                    if (is_array($values['plugin'])) {
                        foreach($values['plugin'] AS $pluginName){
                            $plugins[] = array(
                                'name' => $pluginName
                            );
                        }
                    }
                    $data[$column] = serialize(
                        array('plugins' => $plugins)
                    );
                } else {
                    $data[$column] = $values[$column];
                }
            }

            if ($this->form->isValid($values)) {
                $this->table->insert($data);
                $this->view->message = 'Veiksmīgi pievienots';
                //$this->_forward('index', null, null, array('message' => 'Veiksmīgi pievienots'));
            } else {
                $this->form->populate($values);
            }
        }

        $this->view->form = $this->form;
    }

    public function deleteAction()
    {
        $editId = $this->_getParam('id');

        $where = $this->table->getAdapter()->quoteInto($this->primary.' = ?', $editId);
        $result = $this->table->delete($where);
        $this->_forward('index', null, null, array('message' => 'Veiksmīgi izdzēsts'));
    }


    public function editAction()
    {
        $editId = $this->_getParam('id');
        
        // load row data and save to form
        if (!empty($editId)) {
            $result = $this->table->find($editId);
            $data = $result->toArray();
            
            // set selected plugin form value
            $selected = array();
            $dat = unserialize($data[0]['data']);
            if(is_array($dat['plugins'])){
                foreach($dat['plugins'] AS $plugin){
                    $selected[] = $plugin['name'];
                }
            }
            $data[0]['plugin'] = $selected;

            // order selected list
            $options = array();
            foreach($data[0]['plugin'] AS $sel){
                $options[$sel] = null;
            }
            foreach($this->form->allPlugins AS $key => $val){
                $options[$key] = $val;
            }

            $this->form->removeElement('plugin');
            $this->form->addElement('multiselect', 'plugin',
                array(
                    'label'     => 'Spraudņi:',
                    'filters'   => array('StringTrim', 'StripTags'),
                    'required'  => false,
                    'MultiOptions' => $options,
                    'value'   => $selected,
                    'class' => 'multiselect',
                    'multiple' => 'multiple',
                )
            );

            $this->form->populate($data[0]);
            unset($data);
        }

        // validate form and save new data
        if ($this->_request->isPost()) {
            $values = $this->_request->getPost();
            // prepare values
            foreach ($this->cols AS $column) {
                if ($column == 'data') {
                    /* if plugin, then save in data columns serialized plugin
                     * Array(
                     *       [plugins] => Array(
                     *           [0] => Array(
                     *               [name] => plugin_content
                     *               [id] =>
                     *           )
                     *       )
                     *  )
                     */
                    if (is_array($values['plugin'])) {
                        foreach($values['plugin'] AS $pluginName){
                            $plugins[] = array(
                                'name' => $pluginName,
                            );
                        }
                    }
                    $data[$column] = serialize(
                        array('plugins' => $plugins)
                    );
                } else {
                    $data[$column] = $values[$column];
                }
            }

            if ($this->form->isValid($values) AND !empty($editId)) {
                $where = $this->table->getAdapter()->quoteInto($this->primary.' = ?', $editId);
                $this->table->update($data, $where);

                $this->message->add('Veiksmīgi saglabāts');
                $this->_redirect(
                    $this->url.$this->_helper->url('index').$this->urlParams
                );


            } else {
                $this->form->populate($values);
            }

        }

        $this->view->form = $this->form;
    }


}